// tests/integration_tests.rs
// IndustryAgent 集成测试

use reqwest::Client;
use serde_json::json;
use std::time::Duration;
use tokio::time::timeout;

/// 测试服务器健康检查
#[tokio::test]
async fn test_health_check() {
    let client = Client::new();

    // 等待服务器启动
    tokio::time::sleep(Duration::from_secs(5)).await;

    let response = client
        .get("http://localhost:3030/health")
        .send()
        .await;

    match response {
        Ok(resp) => {
            assert_eq!(resp.status(), 200);
            let body = resp.text().await.unwrap();
            assert!(body.contains("healthy"));
        },
        Err(_) => {
            // 如果服务器未启动，跳过测试
            println!("服务器未启动，跳过健康检查测试");
        }
    }
}

/// 测试版本信息
#[tokio::test]
async fn test_version_info() {
    let client = Client::new();

    let response = client
        .get("http://localhost:3030/version")
        .send()
        .await;

    match response {
        Ok(resp) => {
            assert_eq!(resp.status(), 200);
            let body = resp.text().await.unwrap();
            assert!(body.contains("api_version"));
        },
        Err(_) => {
            println!("服务器未启动，跳过版本信息测试");
        }
    }
}

/// 测试语义转换API
#[tokio::test]
async fn test_semantic_conversion() {
    let client = Client::new();

    let request_body = json!({
        "request_id": "test_conversion_001",
        "data_source_type": "HuaweiCloudIoT",
        "data_source_connection": {
            "connection_type": "HuaweiCloudIoT",
            "connection_string": "test_connection",
            "authentication": {
                "auth_type": "token",
                "token": "test_token"
            },
            "parameters": {}
        },
        "target_opcua_type": "manufacturing_equipment",
        "options": {
            "conversion_mode": "Automatic",
            "quality_level": "Standard",
            "enable_cache": true
        }
    });

    let response = client
        .post("http://localhost:3030/convert")
        .header("Content-Type", "application/json")
        .json(&request_body)
        .send()
        .await;

    match response {
        Ok(resp) => {
            let status = resp.status();
            println!("转换API响应状态: {}", status);

            if status.is_success() {
                let body = resp.text().await.unwrap();
                println!("转换响应: {}", body);
                assert!(body.contains("request_id"));
            } else {
                // 期望可能是错误，因为测试环境可能没有真实的华为云配置
                println!("转换API返回错误状态: {}, 这在测试环境中是正常的", status);
            }
        },
        Err(e) => {
            println!("转换API请求失败: {}", e);
        }
    }
}

/// 测试场景管理
#[tokio::test]
async fn test_scenarios() {
    // 这里可以测试场景管理器的功能
    use industryagent::scenarios::{SceneManager, Scenario};

    let manager = SceneManager::new();

    // 测试场景注册
    let scenarios = manager.list_scenarios();
    assert!(!scenarios.is_empty());

    // 测试制造业场景
    if let Some(manufacturing_scenario) = manager.get_scenario("manufacturing_equipment") {
        assert_eq!(manufacturing_scenario.industry(), "Manufacturing");

        let rules = manufacturing_scenario.get_transformation_rules();
        assert!(!rules.data_source_mappings.is_empty());

        let template = manufacturing_scenario.get_opcua_model_template();
        assert!(!template.namespaces.is_empty());

        let sample_data = manufacturing_scenario.get_sample_data();
        assert!(!sample_data.is_empty());
    }

    // 测试按行业筛选
    let manufacturing_scenarios = manager.get_scenarios_by_industry("Manufacturing");
    assert!(!manufacturing_scenarios.is_empty());

    // 测试统计信息
    let stats = manager.get_statistics();
    assert!(stats.total_scenarios > 0);
}

/// 测试配置加载
#[tokio::test]
async fn test_config_loading() {
    use industryagent::config::Config;

    match Config::load() {
        Ok(config) => {
            // 验证基本配置
            assert!(config.server.port > 0);
            assert!(config.server.workers > 0);
            assert!(!config.huawei_cloud.base_url.is_empty());

            println!("配置加载成功");
            println!("服务器端口: {}", config.server.port);
            println!("华为云API地址: {}", config.huawei_cloud.base_url);
        },
        Err(e) => {
            println!("配置加载失败: {}", e);
        }
    }
}

/// 测试华为云适配器（模拟）
#[tokio::test]
async fn test_huawei_cloud_adapter() {
    use industryagent::adapters::huawei_cloud_adapter::HuaweiCloudAdapter;
    use industryagent::config::HuaweiCloudConfig;

    let config = HuaweiCloudConfig {
        base_url: "https://iotda.cn-north-4.myhuaweicloud.com".to_string(),
        access_token: "test_token".to_string(),
        project_id: "test_project".to_string(),
        timeout_secs: 30,
    };

    let adapter = HuaweiCloudAdapter::new(config);

    // 测试适配器信息
    let info = adapter.get_adapter_info().await.unwrap();
    assert_eq!(info.get("adapter_type").unwrap(), "HuaweiCloud");
    assert_eq!(info.get("platform").unwrap(), "华为云IoTDA");

    // 测试连接（预期失败，因为是测试环境）
    let test_result = adapter.test_connection().await.unwrap();
    assert!(!test_result.success); // 预期失败
    println!("华为云连接测试结果: {}", test_result.message);
}

/// 测试语义转换器
#[tokio::test]
async fn test_semantic_converter() {
    use industryagent::services::semantic_conversion::IndustrialSemanticConverter;
    use industryagent::interfaces::semantic_converter::{
        ConverterConfiguration, ConversionMode, QualityLevel,
        PerformanceSettings, CacheSettings, LoggingSettings, LogLevel
    };

    let config = ConverterConfiguration {
        conversion_mode: ConversionMode::Automatic,
        quality_level: QualityLevel::Standard,
        performance_settings: PerformanceSettings {
            parallelism: 4,
            batch_size: 50,
            memory_limit_mb: 2048,
            timeout_secs: 300,
        },
        cache_settings: CacheSettings {
            enabled: true,
            size_mb: 100,
            ttl_secs: 1800,
            strategy: crate::interfaces::semantic_converter::CacheStrategy::LRU,
        },
        logging_settings: LoggingSettings {
            level: LogLevel::Info,
            verbose: false,
            file_path: None,
            max_file_size_mb: 50,
        },
    };

    let converter = IndustrialSemanticConverter::new(config);

    // 测试配置获取
    let converter_config = converter.get_configuration();
    assert!(matches!(converter_config.conversion_mode, ConversionMode::Automatic));

    // 测试统计信息
    let stats = converter.get_conversion_stats().await.unwrap();
    assert_eq!(stats.total_conversions, 0); // 初始状态
    println!("语义转换器统计信息: {:?}", stats);
}

/// 性能基准测试
#[tokio::test]
async fn test_performance_benchmark() {
    use std::time::Instant;

    println!("开始性能基准测试...");

    // 测试配置加载性能
    let start = Instant::now();
    for _ in 0..100 {
        let _ = industryagent::config::Config::load();
    }
    let config_load_time = start.elapsed();
    println!("100次配置加载耗时: {:?}", config_load_time);

    // 测试场景创建性能
    let start = Instant::now();
    for _ in 0..100 {
        let _ = industryagent::scenarios::SceneManager::new();
    }
    let scene_creation_time = start.elapsed();
    println!("100次场景管理器创建耗时: {:?}", scene_creation_time);

    // 测试JSON序列化性能
    let test_data = json!({
        "device_id": "test_device",
        "status": "Running",
        "temperature": 25.5,
        "timestamp": "2024-01-15T10:30:00Z"
    });

    let start = Instant::now();
    for _ in 0..10000 {
        let _ = serde_json::to_string(&test_data);
    }
    let json_serialization_time = start.elapsed();
    println!("10000次JSON序列化耗时: {:?}", json_serialization_time);
}

/// 并发测试
#[tokio::test]
async fn test_concurrent_requests() {
    use tokio::task::JoinSet;

    let client = Client::new();
    let mut join_set = JoinSet::new();

    // 创建100个并发请求
    for i in 0..100 {
        let client = client.clone();
        join_set.spawn(async move {
            let request_body = json!({
                "request_id": format!("concurrent_test_{}", i),
                "data_source_type": "HuaweiCloudIoT",
                "target_opcua_type": "manufacturing_equipment",
                "options": {
                    "conversion_mode": "Automatic"
                }
            });

            let response = client
                .post("http://localhost:3030/convert")
                .header("Content-Type", "application/json")
                .json(&request_body)
                .send()
                .await;

            match response {
                Ok(resp) => resp.status().as_u16(),
                Err(_) => 0,
            }
        });
    }

    // 等待所有请求完成
    let mut success_count = 0;
    let mut error_count = 0;

    while let Some(result) = join_set.join_next().await {
        match result {
            Ok(status_code) => {
                if status_code >= 200 && status_code < 300 {
                    success_count += 1;
                } else {
                    error_count += 1;
                }
            },
            Err(e) => {
                println!("并发请求失败: {}", e);
                error_count += 1;
            }
        }
    }

    println!("并发测试完成: 成功 {}, 失败 {}", success_count, error_count);
}

/// 错误处理测试
#[tokio::test]
async fn test_error_handling() {
    let client = Client::new();

    // 测试无效的转换请求
    let invalid_request = json!({
        "request_id": "",  // 空的请求ID
        "data_source_type": "InvalidType",  // 无效的数据源类型
        "target_opcua_type": "",  // 空的目标类型
    });

    let response = client
        .post("http://localhost:3030/convert")
        .header("Content-Type", "application/json")
        .json(&invalid_request)
        .send()
        .await;

    match response {
        Ok(resp) => {
            let status = resp.status();
            println!("无效请求响应状态: {}", status);
            // 期望返回错误状态
            assert!(!status.is_success());
        },
        Err(e) => {
            println!("无效请求请求失败: {}", e);
        }
    }

    // 测试不存在的端点
    let response = client
        .get("http://localhost:3030/nonexistent")
        .send()
        .await;

    match response {
        Ok(resp) => {
            assert_eq!(resp.status(), 404);
        },
        Err(e) => {
            println!("不存在端点请求失败: {}", e);
        }
    }
}

/// 内存使用测试
#[tokio::test]
async fn test_memory_usage() {
    // 在真实环境中，这里可以测试内存使用情况
    println!("内存使用测试 - 在生产环境中应该监控内存使用");

    // 创建大量对象测试内存管理
    let mut scenarios = Vec::new();
    for i in 0..1000 {
        let manager = industryagent::scenarios::SceneManager::new();
        scenarios.push(manager);
    }

    println!("创建了 {} 个场景管理器实例", scenarios.len());

    // 清理
    scenarios.clear();
    println!("清理完成");
}